﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace machine_registration.Helpers
{
    using System;
    using System.Collections.ObjectModel;
    using System.Diagnostics;
    using System.IO;
    using System.Text.Json;
    using System.Threading.Tasks;

    public static class JsonFileHelper
    {
        /// <summary>
        /// 将 ObservableCollection 保存为 JSON 文件
        /// </summary>
        /// <param name="data">要保存的数据</param>
        /// <param name="filePath">文件路径</param>
        public static async Task SaveToJsonAsync<T>(ObservableCollection<T> data, string filePath)
        {
            try
            {
                // 序列化为 JSON 字符串
                var json = JsonSerializer.Serialize(data, new JsonSerializerOptions { WriteIndented = true, Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping } );

                // 写入文件
                await File.WriteAllTextAsync(filePath, json);

                Debug.WriteLine("数据已成功保存到 JSON 文件。");
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"保存 JSON 文件时出错: {ex.Message}");
            }
        }

        /// <summary>
        /// 从 JSON 文件中读取 ObservableCollection
        /// </summary>
        /// <param name="filePath">文件路径</param>
        /// <returns>反序列化后的数据</returns>
        public static  ObservableCollection<T> LoadFromJson<T>(string filePath)
        {
            try
            {
                // 读取文件内容
                var json =  File.ReadAllText(filePath);

                // 反序列化为 ObservableCollection
                var data = JsonSerializer.Deserialize<ObservableCollection<T>>(json);

                Debug.WriteLine("数据已成功从 JSON 文件加载。");
                return data;
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"加载 JSON 文件时出错: {ex.Message}");
                return new ObservableCollection<T>();
            }
        }
    }
}
